package com.qianchang.microfinance.view.credit.data;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.TypedValue;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;

import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.ToastUtil;
import com.google.gson.reflect.TypeToken;
import com.qianchang.microfinance.bean.FindGuideBean;
import com.qianchang.microfinance.bean.FindsBean;
import com.qianchang.microfinance.bean.LoanProductBean;
import com.qianchang.microfinance.bean.PageBean;
import com.qianchang.microfinance.bean.RechargeProjectBean;
import com.qianchang.microfinance.bean.event.AgreementEvent;
import com.qianchang.microfinance.bean.event.LoginEvent;
import com.qianchang.microfinance.global.ConstantAppInfo;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseRecyclerAdapter;
import com.qianchang.microfinance.view.base.BaseRecyclerViewFragment;
import com.qianchang.microfinance.view.findings.FindsAdapter;
import com.qianchang.microfinance.view.mine.loan.MyLoanActivity;
import com.qianchang.microfinance.view.mine.loan.MyLoanAdapter;
import com.qianchang.microfinance.view.mine.loan.MyLoanDetailActivity;
import com.qianchang.microfinance.view.mine.loan.RecommendAdapter;
import com.qianchang.microfinance.view.mine.renewal.RenewalAdapter;
import com.qianchang.microfinance.widgets.decoration.SpacesItemDecoration;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

public class RechargeListFragment extends BaseRecyclerViewFragment {
    private static final String TAG = "MyLoanJinbaoFragment";
    private int productType;
    private String urlType;

    private List<FindsBean> listFindBean = new ArrayList<FindsBean>();
    private RecommendAdapter recyclerViewGridAdapter;


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            productType = bundle.getInt(ConstantAppInfo.PROJECT_TYPE);
            urlType = bundle.getString(MyLoanActivity.URL_TYPE);
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        initReCommend();        //初始化我猜你喜欢推荐内容

    }

    @Override
    protected void requestData(HttpParams params) {
        params.put("opSource", 1);
        params.put("maxResults", 10);
        params.put("userId", DMApplication.getInstance().getmUserLoginInfo().getUserId());
        DMOKHttpUtils.getInstance().post(mContext, DMConstant.Config.BASE_USER + "/yeepay/v/findProjectByUserId.do", params, mCallBack);
    }
    @Override
    protected BaseRecyclerAdapter<RechargeProjectBean> getRecyclerAdapter() {
        return new RecharListAdapter(mContext);
    }

    @Override
    protected Type getType() {
        return new TypeToken<PageBean<RechargeProjectBean>>() {
        }.getType();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAgreementSuccessed(AgreementEvent agreementEvent) {
        if (null != agreementEvent && agreementEvent.isSuccess()) {
            initData();
        }
    }


    @Override
    public void onItemClick(int position, long itemId) {
        super.onItemClick(position, itemId);
        RechargeProjectBean loanProductBean = ((RecharListAdapter) mAdapter).getItems().get(position);
        if ("1".equals(loanProductBean.getIsMoneyAuth())) {
            //已认证不作处理
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString(ConstantAppInfo.PROJECT_ID, loanProductBean.getId());
        startActivity(RechargeBankListActivity.class, bundle,true);
    }


    //初始化我猜你喜欢 导流产品
    private void initReCommend() {
        recyclerViewGridAdapter = new RecommendAdapter(getContext(), listFindBean);
        rVrecommend.setAdapter(recyclerViewGridAdapter);
        recyclerViewGridAdapter.setOnItemClickListener(new FindsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                if (position != 5) {
//                    startActivity(DiversionActivity.class);
                    FindsBean findsBean = recyclerViewGridAdapter.getItems().get(position);
                    String mId = findsBean.getId();
                    findGuideUR(mId);

                } else {
                    EventBus.getDefault().post(new LoginEvent(LoginEvent.LoginStatue.LOGOUT_FIND));            //更多选项跳转
                    getActivity().finish();
                }
            }
        });

        RecyclerView.LayoutManager mLayoutManager;
        mLayoutManager = new GridLayoutManager(getContext(), 3, GridLayoutManager.VERTICAL, false);
        final GridLayoutManager manager = (GridLayoutManager) mLayoutManager;
        rVrecommend.setLayoutManager(mLayoutManager);
        //添加ItemDecoration，item之间的间隔
        int leftRight = dip2px(8);
        int topBottom = dip2px(6);
        rVrecommend.addItemDecoration(new SpacesItemDecoration(leftRight, topBottom));

        findThings(); //获取导流产品页面数据

    }

    private WebView webView = null;

    private void initWebView(String url) {
        webView = new WebView(getContext());
        webView.setVisibility(View.VISIBLE);
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.loadUrl(url);
    }


    //调用外部浏览器打开
    private void initWb(String url) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        startActivity(intent);
    }


    public int dip2px(float dpValue) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dpValue, getResources().getDisplayMetrics());
    }


    private void findThings() {

        HttpParams params = new HttpParams();
        params.put("opSource", 1);
        params.put("maxResults", 10);
        DMOKHttpUtils.getInstance().post(getContext(), DMConstant.ApiURL.FINDGUIDELIST, params, new RequestCallBack<PageBean<FindsBean>>() {

            @Override
            public void onSuccess(JsonResult<PageBean<FindsBean>> response) {
                dismiss();
                if (response.getObject() == null) {
                    return;
                }
                PageBean pageBean = response.getObject();
                if (DMConstant.Code.CODE_OK.equals(response.getCode()) && pageBean.getList() != null) {
                    List<FindsBean> listFindBean = pageBean.getList();
                    if (listFindBean != null && listFindBean.size() > 0) {
                        recyclerViewGridAdapter.setData(listFindBean);
                        showIsRecommend(true);      //设置是否显示我猜你喜欢 推荐的产品
                    } else {
                        showIsRecommend(false);      //设置是否显示我猜你喜欢 推荐的产品
                    }
                } else {
                    showIsRecommend(false);      //设置是否显示我猜你喜欢 推荐的产品
                    ToastUtil.getInstant().show(getContext(), response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                showIsRecommend(false);      //设置是否显示我猜你喜欢 推荐的产品
                ToastUtil.getInstant().show(getContext(), msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    //获取导流产品URL
    private void findGuideUR(String id) {

        HttpParams params = new HttpParams();
        params.put("id", id);

        show();
        DMOKHttpUtils.getInstance().post(getContext(), DMConstant.ApiURL.FIND_GUIDE_URL, params, new RequestCallBack<FindGuideBean>() {

            @Override
            public void onSuccess(JsonResult<FindGuideBean> response) {
                dismiss();
                if (DMConstant.Code.CODE_OK.equals(response.getCode())) {
                    FindGuideBean findGuideBean = response.getObject();
                    if (findGuideBean != null) {
                        String url = findGuideBean.getAppURL();
//                        initWebView(url);
                        initWb(url);
                    } else {
                        ToastUtil.getInstant().show(getContext(), "数据有误请稍后再试!");
                    }
                } else {
                    ToastUtil.getInstant().show(getContext(), response.getDescription());
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(getContext(), msg);
            }

            @Override
            public void onConnectFailure(String msg) {
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(TAG);         //友盟统计 Fragment  页面统计
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(TAG);       //友盟统计 Fragment  页面统计
    }

    @Override
    public void onDetach() {
        super.onDetach();
        EventBus.getDefault().unregister(this);
    }
}
